package servlet.user;

import entity.User;
import service.Impl.UserServiceImpl;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user/edit")
public class UserEditServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession();
        User currentUser = (User) session.getAttribute("user"); // 获取当前登录的用户

        if (currentUser == null) {
            resp.sendRedirect(req.getContextPath() + "/login"); // 如果用户未登录，重定向到登录页面
            return;
        }

        Integer id = currentUser.getId(); // 使用当前登录用户的ID
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String ageStr = req.getParameter("age");
        String telephone = req.getParameter("telephone");
        String email = req.getParameter("email");
        String address = req.getParameter("address");
        String pic = req.getParameter("pic");
        String stateStr = req.getParameter("state");

        // 只更新用户提交的信息
        if (userName != null && !userName.isEmpty()) currentUser.setUserName(userName);
        if (password != null && !password.isEmpty()) currentUser.setPassword(password);
        if (sex != null && !sex.isEmpty()) currentUser.setSex(sex);
        if (ageStr != null && !ageStr.isEmpty()) currentUser.setAge(Integer.parseInt(ageStr));
        if (telephone != null && !telephone.isEmpty()) currentUser.setTelephone(telephone);
        if (email != null && !email.isEmpty()) currentUser.setEmail(email);
        if (address != null && !address.isEmpty()) currentUser.setAddress(address);
        if (pic != null && !pic.isEmpty()) currentUser.setPic(pic);
        if (stateStr != null && !stateStr.isEmpty()) currentUser.setState(Integer.parseInt(stateStr));

        userService.updateUser(currentUser); // 更新用户信息
        resp.sendRedirect(req.getContextPath() + "/user/index"); // 重定向到用户主页
    }
}
